package org.budo.spring.velocity.view;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.budo.support.fastjson.Fastjson;
import org.budo.support.mvcs.Mvcs;
import org.budo.support.servlet.util.ResponseUtil;
import org.budo.support.velocity.util.VelocityUtil;

/**
 * @author limingwei
 */
@SuppressWarnings("deprecation")
public class BudoVelocityLayoutView extends org.springframework.web.servlet.view.velocity.VelocityLayoutView {
    private static final String APPLICATION_JSON = "application/json;charset=UTF-8";

    private static final String X_REQUESTED_WITH = "X-Requested-With";

    private static final String AJAX = "Ajax";

    @Override
    protected Template getTemplate() throws Exception {
        return super.getTemplate();
    }

    @Override
    protected Context createVelocityContext(Map<String, Object> model) throws Exception {
        // map put some
        return super.createVelocityContext(model);
    }

    @Override
    protected Template getTemplate(String name) throws Exception {
        String encoding = this.getEncoding();
        VelocityEngine velocityEngine = this.getVelocityEngine();

        if (null != encoding) {
            return velocityEngine.getTemplate(name, encoding);
        }

        return velocityEngine.getTemplate(name);
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        super.render(model, request, response);
    }

    @Override
    protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        super.renderMergedTemplateModel(model, request, response);
    }

    @Override
    protected void doRender(Context context, HttpServletResponse response) throws Exception {
        if (AJAX.equalsIgnoreCase(Mvcs.getRequestHeader(X_REQUESTED_WITH))) {
            Map<String, Object> map = VelocityUtil.contextToMap(context);

            String json = Fastjson.toJSONString(map);
            ResponseUtil.writeToResponse(response, json);
            return;
        }

        super.doRender(context, response);
    }

    @Override
    protected void applyContentType(HttpServletResponse response) {
        if (AJAX.equalsIgnoreCase(Mvcs.getRequestHeader(X_REQUESTED_WITH))) {
            Mvcs.setContentType(response, APPLICATION_JSON);
            return;
        }

        super.applyContentType(response);
    }
}